/*
 * main.cpp
 *
 *  Created on: 23.07.2013
 *      Author: Roma Jam
 */

#include "ch.h"
#include "hal.h"

#include "kl_lib_f4xx.h"
#include "clocking_F40x.h"
#include "cmd_uart.h"

static inline void Init();
void ThreadTask();

static WORKING_AREA(waThdTask, 128);
static msg_t ThdTask(void *arg) {
    (void)arg;
    chRegSetThreadName("Usb2Crd");
    while(1) ThreadTask();
    return 0;
}

// Application entry point
int main(void) {
	// ======= Setup Clock and Core Vcc ======
    Voltage.SetupVcc(Vcc2V7_3V6);
    Clk.SetupFlashLatency(8);
    // HSE 8 Mhz/4 = 2 MHz, 2*192 = 384 MHz, 384/8 = 48 PreAHB, 384/8 = 48 UsbFreq
    Clk.SetupPLLDividers(4, 192, pllSysDiv8, 8);
    // Bus dividers
    Clk.SetupBusDividers(ahbDiv2, apbDiv1, apbDiv1);
    Clk.SwitchToPLL();
    Clk.UpdateFreqValues();

    // ==== Init OS ====
    halInit();
    chSysInit();
    // ==== Init Hard & Soft ====
    Init();

    // Init Thread
    chThdCreateStatic(waThdTask, sizeof(waThdTask), NORMALPRIO, ThdTask, NULL);

    // Setup LEDs on Discovery Board
    PinSetupOut(GPIOD, 12, omPushPull, pudPullUp, ps100MHz); // 12 - Green
    PinSetupOut(GPIOD, 13, omPushPull, pudPullUp, ps100MHz); // 13 - Orange
    PinSetupOut(GPIOD, 14, omPushPull, pudPullUp, ps100MHz); // 14 - Red
    PinSetupOut(GPIOD, 15, omPushPull, pudPullUp, ps100MHz); // 15 - Blue

    while(TRUE) {
    	chThdSleepMilliseconds(999);
	}
}

void ThreadTask() {
	PinToggle(GPIOD, 12);
//	Uart.Printf("a");
	chThdSleepMilliseconds(99);
}

void Init() {
    Uart.Init(57600);
    Uart.Printf("\rChibiOS F4: AHB=%u; APB1=%u; APB2=%u\r", Clk.AHBFreqHz, Clk.APB1FreqHz, Clk.APB2FreqHz);
}
